import * as path from 'node:path';
import type { ConfigEnv, UserConfig } from 'vite';
import { loadEnv } from 'vite';
import { wrapperEnv } from './build/utils';
import { createVitePlugins } from './build/vite/plugin';
import { OUTPUT_DIR } from './build/constant';
import { externalOptions } from './plugin.config';
import dts from 'vite-plugin-dts';
import { generateModifyVars } from './build/generate/generateModifyVars';

// 参考文档
// https://blog.csdn.net/qq_32805013/article/details/134420142

// import commonjs from 'rollup-plugin-commonjs';
// import { exclude, include } from './build/vite/optimize';

function pathResolve(dir: string) {
  return path.resolve(process.cwd(), '.', dir);
}

export default async ({ command, mode }: ConfigEnv): Promise<UserConfig> => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const viteEnv = wrapperEnv(env);
  const { VITE_PORT, VITE_PUBLIC_PATH, VITE_DROP_CONSOLE } = viteEnv;
  const isBuild = command === 'build';

  return {
    base: VITE_PUBLIC_PATH,
    server: {
      host: true,
      port: VITE_PORT
    },
    resolve: {
      alias: [
        {
          find: /\@\//,
          replacement: `${pathResolve('packages')}/`
        },
        {
          find: /\~\//,
          replacement: `${pathResolve('src')}/`
        }
      ]
    },
    esbuild: {
      drop: VITE_DROP_CONSOLE ? ['console', 'debugger'] : []
    },
    define: {
      __APP_INFO__: JSON.stringify({}),
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'true'
    },
    plugins: [
      ...createVitePlugins(viteEnv, isBuild),
      dts({
        outDir: [pathResolve('./libs')],
        tsconfigPath: pathResolve('./tsconfig.app.json')
      })
    ],
    build: {
      outDir: OUTPUT_DIR,
      target: 'modules',
      minify: 'terser', // 'esbuild'
      cssTarget: 'chrome80',
      terserOptions: {
        compress: {
          keep_infinity: true,
          drop_console: VITE_DROP_CONSOLE
        }
      },
      cssCodeSplit: true,
      reportCompressedSize: false,
      chunkSizeWarningLimit: 2000,
      lib: {
        entry: pathResolve('./packages/index.ts'),
        name: 'TyndallSchema',
        formats: ['es', 'cjs', 'umd', 'iife'], // , 'iife'  // 'es' | 'cjs' | 'umd' | 'iife'
        fileName: formart => `hickey-ui.${formart}.js`
      },
      rollupOptions: {
        treeshake: {
          // treeshake 配置选项
          moduleSideEffects: false
        },
        external: Object.keys(externalOptions),
        // output: {
        //   globals: externalOptions,
        // }
        output: [
          {
            format: 'es',
            entryFileNames: '[name].js',
            preserveModules: true, // 让打包目录和我们目录对应
            exports: 'named',
            globals: externalOptions,
            dir: pathResolve('./libs')
          },
          {
            format: 'es',
            entryFileNames: 'hickey-ui.es.js', // 不用打包成.es.js,这里我们想把它打包成.js
            exports: 'named',
            globals: externalOptions,
            dir: pathResolve('./libs')
          },
          {
            format: 'cjs',
            entryFileNames: 'hickey-ui.cjs.js',
            globals: externalOptions,
            // preserveModules: true,
            exports: 'named',
            dir: pathResolve('./libs')
          },
          {
            name: 'TyndallSchema',
            format: 'umd',
            exports: 'named',
            globals: externalOptions,
            dir: pathResolve('./libs')
          },
          {
            name: 'TyndallSchema',
            format: 'iife',
            exports: 'named',
            globals: externalOptions,
            dir: pathResolve('./libs')
          }
        ]
      }
    },
    css: {
      devSourcemap: true,
      preprocessorOptions: {
        preserveModules: true,
        less: {
          modifyVars: generateModifyVars(),
          javascriptEnabled: true
        }
      }
    }
  };
};
